export const getOpenAIStreamResponse = async (userInput, onStream, signal) => {
  const url = "https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions";
  const apiKey = "sk-392a31726d4e4124a062d476c25cc5fa";

  const body = {
    model: "deepseek-r1",
    messages: [{ role: "user", content: userInput }],
    stream: true, // 启用流式传输
  };

  try {
    const response = await fetch(url, {
      method: "POST",
      headers: {
        "Content-Type": "application/json",
        Authorization: `Bearer ${apiKey}`,
      },
      body: JSON.stringify(body),
      signal, // 传递AbortSignal以支持取消
    });

    if (!response.ok) {
      const errorData = await response.json();
      throw new Error(errorData.error?.message || "请求失败");
    }

    // 处理流式响应
    const reader = response.body.getReader();
    const decoder = new TextDecoder("utf-8");
    let partialLine = "";

    while (true) {
      const { value, done } = await reader.read();
      if (done) break;

      const chunk = decoder.decode(value, { stream: true });
      const lines = (partialLine + chunk).split("\n");
      partialLine = lines.pop() || ""; // 保存未完成的行

      for (const line of lines) {
        if (line.trim() === "") continue;
        if (line.trim() === "data: [DONE]") return;

        try {
          const json = JSON.parse(line.replace("data: ", ""));
          const content = json.choices[0]?.delta?.content || "";
          if (content) onStream(content); // 实时回调内容
        } catch (err) {
          console.error("解析错误:", err);
        }
      }
    }
  } catch (error) {
    if (error.name === "AbortError") {
      console.log("请求已取消");
      return;
    }
    console.error("API错误:", error);
    throw new Error(`请求失败: ${error.message}`);
  }
};